package com.funsport.controller.mobile;

import com.funsport.common.Result;
import com.funsport.entity.*;
import com.funsport.service.*;
import com.funsport.security.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 移动端收藏控制器
 */
@Slf4j
@Tag(name = "移动端收藏管理")
@RestController
@RequestMapping("/mobile/favorite")
@RequiredArgsConstructor
public class MobileFavoriteController {
    
    private final IFavoriteService favoriteService;
    private final IEventService eventService;
    private final IClubService clubService;
    private final ICommunityPostService communityPostService;
    
    @Operation(summary = "收藏活动")
    @PostMapping("/event/{eventId}")
    public Result<Void> favoriteEvent(@PathVariable Long eventId) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 检查活动是否存在
        Event event = eventService.getById(eventId);
        if (event == null) {
            return Result.error("活动不存在");
        }
        
        boolean success = favoriteService.addFavorite(userId, "event", eventId);
        return success ? Result.success() : Result.error("收藏失败");
    }
    
    @Operation(summary = "取消收藏活动")
    @DeleteMapping("/event/{eventId}")
    public Result<Void> unfavoriteEvent(@PathVariable Long eventId) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean success = favoriteService.removeFavorite(userId, "event", eventId);
        return success ? Result.success() : Result.error("取消收藏失败");
    }
    
    @Operation(summary = "检查是否收藏活动")
    @GetMapping("/event/{eventId}/check")
    public Result<Boolean> checkEventFavorite(@PathVariable Long eventId) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean isFavorited = favoriteService.isFavorited(userId, "event", eventId);
        return Result.success(isFavorited);
    }
    
    @Operation(summary = "获取收藏的活动列表")
    @GetMapping("/events")
    public Result<List<Event>> getFavoriteEvents() {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 获取收藏的活动ID列表
        List<Long> eventIds = favoriteService.getUserFavoriteIds(userId, "event");
        
        if (eventIds.isEmpty()) {
            return Result.success(Collections.emptyList());
        }
        
        // 批量查询活动详情
        List<Event> events = eventService.listByIds(eventIds);
        
        // 按收藏时间排序（保持收藏顺序）
        Map<Long, Integer> orderMap = new HashMap<>();
        for (int i = 0; i < eventIds.size(); i++) {
            orderMap.put(eventIds.get(i), i);
        }
        
        events.sort((e1, e2) -> {
            Integer order1 = orderMap.getOrDefault(e1.getId(), Integer.MAX_VALUE);
            Integer order2 = orderMap.getOrDefault(e2.getId(), Integer.MAX_VALUE);
            return order1.compareTo(order2);
        });
        
        return Result.success(events);
    }
    
    @Operation(summary = "收藏俱乐部")
    @PostMapping("/club/{clubId}")
    public Result<Void> favoriteClub(@PathVariable Long clubId) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 检查俱乐部是否存在
        Club club = clubService.getById(clubId);
        if (club == null) {
            return Result.error("俱乐部不存在");
        }
        
        boolean success = favoriteService.addFavorite(userId, "club", clubId);
        return success ? Result.success() : Result.error("收藏失败");
    }
    
    @Operation(summary = "取消收藏俱乐部")
    @DeleteMapping("/club/{clubId}")
    public Result<Void> unfavoriteClub(@PathVariable Long clubId) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean success = favoriteService.removeFavorite(userId, "club", clubId);
        return success ? Result.success() : Result.error("取消收藏失败");
    }
    
    @Operation(summary = "检查是否收藏俱乐部")
    @GetMapping("/club/{clubId}/check")
    public Result<Boolean> checkClubFavorite(@PathVariable Long clubId) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean isFavorited = favoriteService.isFavorited(userId, "club", clubId);
        return Result.success(isFavorited);
    }
    
    @Operation(summary = "获取收藏的俱乐部列表")
    @GetMapping("/clubs")
    public Result<List<Club>> getFavoriteClubs() {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 获取收藏的俱乐部ID列表
        List<Long> clubIds = favoriteService.getUserFavoriteIds(userId, "club");
        
        if (clubIds.isEmpty()) {
            return Result.success(Collections.emptyList());
        }
        
        // 批量查询俱乐部详情
        List<Club> clubs = clubService.listByIds(clubIds);
        
        // 按收藏时间排序
        Map<Long, Integer> orderMap = new HashMap<>();
        for (int i = 0; i < clubIds.size(); i++) {
            orderMap.put(clubIds.get(i), i);
        }
        
        clubs.sort((c1, c2) -> {
            Integer order1 = orderMap.getOrDefault(c1.getId(), Integer.MAX_VALUE);
            Integer order2 = orderMap.getOrDefault(c2.getId(), Integer.MAX_VALUE);
            return order1.compareTo(order2);
        });
        
        return Result.success(clubs);
    }
    
    @Operation(summary = "收藏帖子")
    @PostMapping("/post/{postId}")
    public Result<Void> favoritePost(@PathVariable Long postId) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 检查帖子是否存在
        CommunityPost post = communityPostService.getById(postId);
        if (post == null) {
            return Result.error("帖子不存在");
        }
        
        boolean success = favoriteService.addFavorite(userId, "post", postId);
        return success ? Result.success() : Result.error("收藏失败");
    }
    
    @Operation(summary = "取消收藏帖子")
    @DeleteMapping("/post/{postId}")
    public Result<Void> unfavoritePost(@PathVariable Long postId) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean success = favoriteService.removeFavorite(userId, "post", postId);
        return success ? Result.success() : Result.error("取消收藏失败");
    }
    
    @Operation(summary = "检查是否收藏帖子")
    @GetMapping("/post/{postId}/check")
    public Result<Boolean> checkPostFavorite(@PathVariable Long postId) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean isFavorited = favoriteService.isFavorited(userId, "post", postId);
        return Result.success(isFavorited);
    }
    
    @Operation(summary = "获取收藏的帖子列表")
    @GetMapping("/posts")
    public Result<List<CommunityPost>> getFavoritePosts() {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 获取收藏的帖子ID列表
        List<Long> postIds = favoriteService.getUserFavoriteIds(userId, "post");
        
        if (postIds.isEmpty()) {
            return Result.success(Collections.emptyList());
        }
        
        // 批量查询帖子详情
        List<CommunityPost> posts = communityPostService.listByIds(postIds);
        
        // 按收藏时间排序
        Map<Long, Integer> orderMap = new HashMap<>();
        for (int i = 0; i < postIds.size(); i++) {
            orderMap.put(postIds.get(i), i);
        }
        
        posts.sort((p1, p2) -> {
            Integer order1 = orderMap.getOrDefault(p1.getId(), Integer.MAX_VALUE);
            Integer order2 = orderMap.getOrDefault(p2.getId(), Integer.MAX_VALUE);
            return order1.compareTo(order2);
        });
        
        return Result.success(posts);
    }
    
    @Operation(summary = "获取收藏统计")
    @GetMapping("/stats")
    public Result<Map<String, Integer>> getFavoriteStats() {
        Long userId = SecurityUtils.getCurrentUserId();
        
        Map<String, Integer> stats = new HashMap<>();
        stats.put("events", favoriteService.getUserFavoriteIds(userId, "event").size());
        stats.put("clubs", favoriteService.getUserFavoriteIds(userId, "club").size());
        stats.put("posts", favoriteService.getUserFavoriteIds(userId, "post").size());
        
        return Result.success(stats);
    }
}

